let utils = require('./utils');
let constants = require('./constants');
let Session = require('./session');
let api = require('./api');

/***
 * @class
 * 表示登录过程中发生的异常
 */
let LoginError = (function () {
    function LoginError(type, message) {
        Error.call(this, message);
        this.type = type;
        this.message = message;
    }

    LoginError.prototype = new Error();
    LoginError.prototype.constructor = LoginError;

    return LoginError;
})();

/**
 * 微信登录，获取 code 和 encryptData
 */
let getWxLoginResult = function getLoginCode(callback) {
    wx.login({
        success: function (loginResult) {
            wx.getUserInfo({
                withCredentials: true,
                lang: 'zh_CN',
                success: function (userResult) {
                    callback(null, {
                        code: loginResult.code,
                        encryptedData: userResult.encryptedData,
                        iv: userResult.iv,
                        rawData: userResult.rawData,
                        userInfo: userResult.userInfo,
                        hasAuth: 1
                    });
                },

                fail: function (userError) {
                    let error = new LoginError(constants.ERR_WX_NOT_AUTHORIZATION, '用户没有授权');
                    callback(error, null);
                }
            });

        },

        fail: function (loginError) {
            let error = new LoginError(constants.ERR_WX_LOGIN_FAILED, '微信登录失败，请检查网络状态');
            callback(error, null);
        }
    });
};

let noop = function noop() {
};
let defaultOptions = {
    method: 'GET',
    success: noop,
    fail: noop,
    loginUrl: null,
};

/**
 * @method
 * 进行服务器登录，以获得登录会话
 *
 * @param {Object} options 登录配置
 * @param {string} options.loginUrl 登录使用的 URL，服务器应该在这个 URL 上处理登录请求
 * @param {string} [options.method] 请求使用的 HTTP 方法，默认为 "GET"
 * @param {Function} options.success(userInfo) 登录成功后的回调函数，参数 userInfo 微信用户信息
 * @param {Function} options.fail(error) 登录失败后的回调函数，参数 error 错误信息
 */
let login = function login(options) {
    options = utils.extend({}, defaultOptions, options);
    let doLogin = () => getWxLoginResult(function (wxLoginError, wxLoginResult) {
        if (wxLoginError) {
            options.fail(wxLoginError);
            return;
        }

        // 构造请求头，包含 code、encryptedData 和 iv
        let code = wxLoginResult.code;
        let encryptedData = wxLoginResult.encryptedData;
        let iv = wxLoginResult.iv;
        let rawData = wxLoginResult.rawData;
        let hasAuth = wxLoginResult.hasAuth;
        let userInfo = wxLoginResult.userInfo;

        let header = {}
        header[constants.WX_HEADER_RAWDATA] = encodeURIComponent(rawData);
        header[constants.WX_HEADER_CODE] = code;
        header[constants.WX_HEADER_ENCRYPTED_DATA] = encryptedData;
        header[constants.WX_HEADER_IV] = iv;
        header[constants.WX_HASAUTH] = hasAuth;

        // 业务系统请求头信息
        header["Content-Type"] = "application/json";
        header["organId"] = "1000000";
        header["clientId"] = "ALT";
        header["clientSecret"] = "48CD11D8EF0F45935AA2BE33C52764EA";
        header["scope"] = "01";
        header["version"] = 'ALT:V1.0.0';

        // 请求服务器登录地址，获得会话信息
        wx.request({
            url: api.login,
            header: header,
            method: options.method,
            data: options.data,
            success: function (result) {
                if (result.data.code == 200) {
                    let session = {
                        loginInfo: {
                            accessToken: result.data.data.accessToken,
                            organId: result.data.data.organId,
                            expireIn: result.data.data.expireIn
                        },
                        userInfo: userInfo
                    }
                    Session.set(session);
                    options.success(result.data);
                } else {
                    options.fail(result.data);
                }
            },
            // 响应错误
            fail: function (loginResponseError) {
                let error = new LoginError(constants.ERR_LOGIN_FAILED, '登录失败，可能是网络异常，请稍后再试');
                options.fail(error);
            },
        });
    });

    let session = Session.get();
    if (session && session.userInfo) {
        wx.checkSession({
            success: function () {
                options.success(session.userInfo);
            },
            fail: function () {
                Session.clear();
                doLogin();
            },
        });
    } else {
        doLogin();
    }
};

let login2 = function login2(options) {
    wx.login({
        success: function (loginResult) {
            let code = loginResult.code;
            let userResult = options.userResult
            let encryptedData = userResult.encryptedData;
            let iv = userResult.iv;
            let rawData = userResult.rawData;
            let hasAuth = 2;
            let header = {}

            header[constants.WX_HEADER_RAWDATA] = encodeURIComponent(rawData);
            header[constants.WX_HEADER_CODE] = code;
            header[constants.WX_HEADER_ENCRYPTED_DATA] = encryptedData;
            header[constants.WX_HEADER_IV] = iv;
            header[constants.WX_HASAUTH] = hasAuth;

            // 业务系统请求头信息
            header["Content-Type"] = "application/json";
            header["organId"] = "1000000";
            header["clientId"] = "ALT";
            header["clientSecret"] = "48CD11D8EF0F45935AA2BE33C52764EA";
            header["scope"] = "01";
            header["version"] = 'ALT:V1.0.0';

            // 请求服务器登录地址，获得会话信息
            wx.request({
                url: api.login,
                header: header,
                method: "POST",
                success: function (result) {
                    // let json = result.data;
                    // // 成功地响应会话信息
                    // if (typeof json == 'string') {
                    //   json = json.trim();
                    //   json = JSON.parse(json);
                    // }

                    // if (json && json.code > 0) {
                    //   let session = {
                    //     token: json.data.token,
                    //     userInfo: json.data,
                    //     hasUserInfo: true
                    //   }
                    //   Session.set(session);
                    //   options.success(json.data);
                    // } else {
                    //   let errorMessage = (json.msg || '未知错误');
                    //   let noSessionError = new LoginError(constants.ERR_LOGIN_SESSION_NOT_RECEIVED, errorMessage);
                    //   options.fail(noSessionError);
                    // }
                },

                // 响应错误
                fail: function (loginResponseError) {
                    let error = new LoginError(constants.ERR_LOGIN_FAILED, '登录失败，可能是网络异常，请稍后再试');
                    options.fail(error);
                },
            });
        },
        fail: function (loginResult) {

        }
    })
}


module.exports = {
    LoginError: LoginError,
    login: login,
    login2: login2
};
